<template>
  <div class="scheduled-task-list page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">定时任务列表</h1>
        <p class="page-subtitle">
          管理系统定时任务，查看任务执行状态和手动操作
        </p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-select
          v-model="searchForm.taskType"
          placeholder="任务类型"
          clearable
          class="type-select"
        >
          <el-option label="订单超时任务" value="ORDER_TIMEOUT" />
          <el-option label="微信支付回调" value="WX_PAY_CALLBACK" />
        </el-select>
        <el-select
          v-model="searchForm.status"
          placeholder="任务状态"
          clearable
          class="status-select"
        >
          <el-option label="待执行" :value="0" />
          <el-option label="执行中" :value="1" />
          <el-option label="执行成功" :value="2" />
          <el-option label="执行失败" :value="3" />
          <el-option label="已取消" :value="4" />
          <el-option label="已暂停" :value="5" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="taskList"
        style="width: 100%"
        class="task-table"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="id"
          label="任务ID"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="taskType"
          label="任务类型"
          width="150"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getTaskTypeTagType(row.taskType)" size="small">
              {{ getTaskTypeText(row.taskType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="businessId"
          label="业务ID"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="executeTime"
          label="计划执行时间"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="runsCount"
          label="执行次数"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span class="retry-count">
              {{ row.runsCount }}/{{ row.maxRunsCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="cron"
          label="Cron表达式"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="errorMsg"
          label="执行结果"
          width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.errorMsg" class="error-msg">
              {{ row.errorMsg }}
            </span>
            <span v-else class="no-error">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建时间"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column
          prop="modifiedTime"
          label="更新时间"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column
          prop="remark"
          label="备注"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="executeTask(row)"
                class="action-btn"
                v-if="[0, 3, 5].includes(row.status)"
              >
                手动执行
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="cancelTask(row)"
                class="action-btn"
                v-if="[3, 5].includes(row.status)"
              >
                取消
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface ScheduledTaskVO {
  id: string;
  taskType: string;
  businessId: string;
  businessData: string | null;
  executeTime: string;
  status: number;
  runsCount: number;
  maxRunsCount: number;
  cron: string;
  errorMsg: string | null;
  createdTime: string;
  modifiedTime: string;
  remark: string;
}

const loading = ref(false);
const taskList = ref<ScheduledTaskVO[]>([]);

// 搜索表单
const searchForm = ref({
  taskType: "",
  status: "",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取任务类型文本
const getTaskTypeText = (taskType: string): string => {
  const typeMap: Record<string, string> = {
    ORDER_TIMEOUT: "订单超时任务",
    WX_PAY_CALLBACK: "微信支付回调",
  };
  return typeMap[taskType] || taskType;
};

// 获取任务类型标签类型
const getTaskTypeTagType = (taskType: string): string => {
  const typeMap: Record<string, string> = {
    ORDER_TIMEOUT: "warning",
    WX_PAY_CALLBACK: "primary",
  };
  return typeMap[taskType] || "info";
};

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "待执行",
    1: "执行中",
    2: "执行成功",
    3: "执行失败",
    4: "已取消",
    5: "已暂停",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态标签类型
const getStatusTagType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "info", // 待执行
    1: "primary", // 执行中
    2: "success", // 执行成功
    3: "danger", // 执行失败
    4: "warning", // 已取消
    5: "warning", // 已暂停
  };
  return typeMap[status] || "info";
};

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true;
  try {
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      taskType: searchForm.value.taskType || "",
      status: searchForm.value.status !== "" ? searchForm.value.status : "",
    };

    const res = await postWithAuth("/internal/scheduled/scheduledPage", params);
    if (res.code === 0 && res.data) {
      taskList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = Number(res.data.total || 0);
    } else {
      taskList.value = [];
      total.value = 0;
      ElMessage.error(res.message || "获取任务列表失败");
    }
  } catch (error) {
    console.error("获取任务列表失败:", error);
    ElMessage.error("获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchTaskList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    taskType: "",
    status: "",
  };
  currentPage.value = 1;
  fetchTaskList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchTaskList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchTaskList();
};

// 手动执行任务
const executeTask = async (row: ScheduledTaskVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要手动执行任务"${row.id}"吗？`,
      "确认执行",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth(
      "/internal/scheduled/execute/" + row.id,
      {}
    );

    if (response.code === 0) {
      ElMessage.success("任务执行成功");
      fetchTaskList();
    } else {
      ElMessage.error(response.message || "任务执行失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("执行任务失败:", error);
      ElMessage.error("执行任务失败");
    }
  }
};

// 取消任务
const cancelTask = async (row: ScheduledTaskVO) => {
  try {
    await ElMessageBox.confirm(`确定要取消任务"${row.id}"吗？`, "确认取消", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await postWithAuth("/internal/scheduled/cancel", {
      taskId: row.id,
    });

    if (response.code === 0) {
      ElMessage.success("任务取消成功");
      fetchTaskList();
    } else {
      ElMessage.error(response.message || "取消任务失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消任务失败:", error);
      ElMessage.error("取消任务失败");
    }
  }
};

onMounted(() => {
  fetchTaskList();
});
</script>

<style scoped>
.scheduled-task-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.type-select,
.status-select {
  width: 150px;
}

.task-table {
  margin: 0;
}

.retry-count {
  font-weight: 500;
  color: #6b7280;
}

.error-msg {
  /* color: #ef4444; */
  font-size: 12px;
}

.no-error {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  margin: 0;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f3f4f6;
}

/* 平板端适配 */
@media (max-width: 1024px) {
  .search-section {
    flex-wrap: wrap;
    gap: 12px;
  }

  .type-select,
  .status-select {
    width: 140px;
  }
}

/* 手机端适配 */
@media (max-width: 768px) {
  .scheduled-task-list {
    padding: 16px;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .type-select,
  .status-select {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .action-btn {
    width: 100%;
  }
}
</style>
